import 'package:flutter/material.dart';
import 'package:live_flutter_plugin/manager/tx_audio_effect_manager.dart';
import 'package:live_flutter_plugin/manager/tx_beauty_manager.dart';
import 'package:live_flutter_plugin/manager/tx_device_manager.dart';
import 'package:live_flutter_plugin/v2_tx_live_code.dart';
import 'package:live_flutter_plugin/v2_tx_live_def.dart';
import 'package:live_flutter_plugin/v2_tx_live_premier.dart';
import 'package:live_flutter_plugin/v2_tx_live_pusher.dart';
import 'package:live_flutter_plugin/v2_tx_live_pusher_observer.dart';
import 'package:live_flutter_plugin/widget/v2_tx_live_video_widget.dart';
import 'package:permission_handler/permission_handler.dart';

class LiveCameraPush extends StatefulWidget {
  // final V2TXLiveMode liveMode;
  // final V2TXLiveAudioQuality audioQuality;
  // final String streamId;

  // const LiveCameraPush(
  //     {Key? key,
  //     required this.audioQuality,
  //     required this.streamId,
  //     required this.liveMode})
  //     : super(key: key);

  State<StatefulWidget> createState() {
    return _LiveCameraPusherPageState();
  }
}

class _LiveCameraPusherPageState extends State<LiveCameraPush> {
  V2TXLivePusher? _livePusher;

  /// 当前音频质量
  V2TXLiveAudioQuality _audioQuality =
      V2TXLiveAudioQuality.v2TXLiveAudioQualityDefault;

  /// 分辨率
  V2TXLiveVideoResolution _resolution =
      V2TXLiveVideoResolution.v2TXLiveVideoResolution1280x720;

  /// 旋转角度
  V2TXLiveRotation _liveRotation = V2TXLiveRotation.v2TXLiveRotation0;

  /// 摄像头
  V2TXLiveMirrorType _liveMirrorType =
      V2TXLiveMirrorType.v2TXLiveMirrorTypeAuto;

  // 音频设置
  bool _microphoneEnable = true;
  TXDeviceManager? _txDeviceManager;
  TXBeautyManager? _txBeautyManager;
  TXAudioEffectManager? _txAudioEffectManager;
  int? _localViewId;

  /// 初始化渲染视图
  @override
  void initState() {
    super.initState();
    setupLicense();
    initLive();
  }

  /// 组件被移除，不可见
  @override
  void deactivate() {
    super.deactivate();
  }

  /// 组件被永久移除，销毁
  @override
  dispose() {
    super.dispose();
  }

  initLive() async {
    await initPlatformState();
    // // 获取设备管理模块
    _txDeviceManager = _livePusher?.getDeviceManager();
    // 获取美颜管理对象
    _txBeautyManager = _livePusher?.getBeautyManager();
    // 获取音效管理类
    _txAudioEffectManager = _livePusher?.getAudioEffectManager();
  }

  // 初始化直播对象
  Future<void> initPlatformState() async {
    _livePusher = V2TXLivePusher(V2TXLiveMode.v2TXLiveModeRTMP);
    _livePusher?.addListener(onPusherObserver);

    /// 申请摄像头、麦克风权限
    // requestAllPermissioin();

    if (!mounted) return;
    setState(() {
      debugPrint("CreatePusher result is ${_livePusher?.status}");
    });
  }

  onPusherObserver(V2TXLivePusherListenerType type, param) {
    debugPrint("==pusher listener type= ${type.toString()}");
    debugPrint("==pusher listener param= $param");
  }

  /// 腾讯云License管理页面(https://console.cloud.tencent.com/live/license)
  setupLicense() {
    // 当前应用的License LicenseUrl
    var LICENSEURL =
        'https://license.vod2.myqcloud.com/license/v2/1302320471_1/v_cube.license';
    // 当前应用的License Key
    var LICENSEURLKEY = '24ac218b69053bad3e33b6dcd6625ffb';
    V2TXLivePremier.setObserver(onPremierObserver);
    V2TXLivePremier.setLicence(LICENSEURL, LICENSEURLKEY);
  }

  onPremierObserver(V2TXLivePremierObserverType type, param) {
    // debugPrint("==premier listener type= ${type.toString()}");
    // debugPrint("==premier listener param= $param");
  }

  // 申请权限
  void requestAllPermissioin() async {
    if (await Permission.contacts.request().isGranted) {}

    Map<Permission, PermissionStatus> statuses = await [
      Permission.camera,
      Permission.microphone,
    ].request();
    print('申请权限=========');
    print(statuses[Permission.camera]);
  }

  // 开始推流
  startPush() async {
    if (_livePusher == null) {
      return;
    }
    await _livePusher?.setRenderMirror(_liveMirrorType);
    var videoEncoderParam = V2TXLiveVideoEncoderParam();
    videoEncoderParam.videoResolution = _resolution;
    videoEncoderParam.videoResolutionMode =
        V2TXLiveVideoResolutionMode.v2TXLiveVideoResolutionModePortrait;
    await _livePusher?.setVideoQuality(videoEncoderParam);
    await _livePusher?.setAudioQuality(_audioQuality);

    // 设置视频渲染View
    if (_localViewId != null) {
      var code = await _livePusher?.setRenderViewID(_localViewId!);
      if (code != V2TXLIVE_OK) {
        print("StartPush error： please check remoteView load");
        return;
      }
    }
    // 开启摄像头预览
    var cameraCode = await _livePusher?.startCamera(true);
    if (cameraCode == null || cameraCode != V2TXLIVE_OK) {
      return;
    }
    print('摄像头预览成功');
    var url =
        'rtmp://lmsv-test-hw.guangbei168.com/guangbei/96039122-2711-28?txSecret=4bf0e9f935d50e11c1290a49dfadc680&txTime=62a82c1b';
    var pushCode = await _livePusher?.startPush(url);
    if (pushCode == null || pushCode != V2TXLIVE_OK) {
      print('推流失败${pushCode}');
      return;
    }
    print('推流成功');
    // 开启麦克风
    if (_microphoneEnable) {
      await _livePusher?.startMicrophone();
    }
    var isFrontCamera = await _txDeviceManager?.isFrontCamera();
    debugPrint("current device isFrontCamera: $isFrontCamera");
  }

  // 视频渲染View Widget
  bool _isStartPush = false;
  Widget renderView() {
    return V2TXLiveVideoWidget(
      onViewCreated: (viewId) async {
        _localViewId = viewId;
        if (_isStartPush == false) {
          _isStartPush = true;
          Future.delayed(const Duration(seconds: 1), () {
            startPush();
          });
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: double.infinity,
      color: Colors.black,
      child: Center(
        child: renderView(),
      ),
    );
  }
}
